package com.qf.j2112.service;

import com.qf.j2112.po.SysOrder;
import com.qf.j2112.vo.Chargevo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.UUID;

/**
 * @ProjectName: YiZhanXiYi
 * @Package: com.qf.j2112.service
 * @ClassName: ProdService
 * @Author: 宋晓博
 * @Description: description
 * @Date: 2022/4/22 16:01
 * @Version: 1.0
 */

@Component
@Slf4j
public class RabbitService implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnCallback{

    @Autowired
    RabbitTemplate rabbitTemplate;

    @PostConstruct  //在对象创建完成时，调用来初始化对象
    public void init(){
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }

    //发送余额抵扣消息
    public void sendReduceRequest(SysOrder sysOrder){
        log.info("send order:"+sysOrder);
        String id = UUID.randomUUID().toString();
        CorrelationData correlationData = new CorrelationData(id);//创建一个协调对象
        log.info("send msg id:"+id);
        rabbitTemplate.convertAndSend("topicExchange","reduceMoneyQueue",sysOrder,correlationData);
    }

    //发送充值消息
    public void sendChargeRequest(Chargevo chargevo){
        log.info("send chargevo:"+chargevo);
        String id = UUID.randomUUID().toString();
        CorrelationData correlationData = new CorrelationData(id);//创建一个协调对象
        log.info("send msg id:"+id);
        rabbitTemplate.convertAndSend("topicExchange","chargeQueue",chargevo,correlationData);
    }

    //    消息发送至交换机 返馈的回调函数
    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        log.info("correlationData:"+correlationData);
        log.info("消息发送是否成功："+b);
        log.info("消息发送失败原因："+s);

    }
//  消息由交换机发送至消息队列的回调确认
    /**
     * Message message, 消息的封装
     * int replyCode, 返回状态码
     * String replyText, 返馈文本
     * String exchange, 交换机名
     * String routingKey  路由凭证
     */

    @Override
    public void returnedMessage(Message message, int i, String s, String s1, String s2) {
        log.info("message:"+message);
        log.info("statusCode:"+ i);
        log.info("reply-text:"+s);
        log.info("excahnge:"+s1);
        log.info("routingkey:"+s2);
    }
}
